﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using AutoMapper;
using Fake_Shop_WebApi.Dtos;
using Fake_Shop_WebApi.Helper;
using Fake_Shop_WebApi.Models;
using Fake_Shop_WebApi.ResourceParameters;
using Fake_Shop_WebApi.Services;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.JsonPatch;
using Microsoft.AspNetCore.Mvc;

// For more information on enabling Web API for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860
/*
 * PUT  更新某资源的全部信息    该资源的全部字段    当某些字段被忽略后，信息会被删除
 * PATCH  更新某资源的部分信息  该资源需要被更新的部分字段      patch是在put 之后才被提出来的
 */


namespace Fake_Shop_WebApi.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class TouristRoutesController : ControllerBase
    {
        private ITouristRouteRepository _touristRouteRepository;
        private readonly IMapper _mapper;
        public TouristRoutesController(ITouristRouteRepository touristRouteRepository,IMapper mapper)
        {
            _touristRouteRepository = touristRouteRepository;
            _mapper = mapper;
        }
        [HttpGet]
        [HttpHead]
        public async Task<IActionResult> GerTouristRoutes(
            [FromQuery] TouristRouteResourceParamaters paramaters
            /*[FromQuery] string keyword,string rating*/)
        {
            //Regex regex = new Regex(@"([a-zA-Z0-9\-]+)(\d+)");
            //string ratingOperator = "";
            //int ratingValue = -1;
            //Match math = regex.Match(rating);
            //if (math.Success)
            //{
            //    ratingOperator = math.Groups[1].Value;
            //    ratingValue = int.Parse(math.Groups[2].Value);
            //}
            var touristRoutesFromRepo = await _touristRouteRepository.GetTouristRoutesAsync(paramaters.keyword, paramaters.ratingOperator, paramaters.ratingValue);
            if(touristRoutesFromRepo==null || touristRoutesFromRepo.Count() <= 0)
            {
                return NotFound("没有旅游路线");
            }
            var touristRoutesFromDto = _mapper.Map<IEnumerable<TouristRouteDto>>(touristRoutesFromRepo);
            return Ok(touristRoutesFromDto);
        }
        [HttpGet("{tourisId}",Name = "GerTouristRoutesById")]
        [HttpHead]
        public async Task<IActionResult> GerTouristRoutesById(Guid tourisId)
        {
            var touristRouteFromRepo =await  _touristRouteRepository.GetTouristRouteAsync(tourisId);
            if (touristRouteFromRepo == null)
            {
                return NotFound($"找不到旅游路线Id为{tourisId}的路线");
            }
            //var touristRouteDto = new TouristRouteDto()
            //{
            //    Id = touristRouteFromRepo.Id,
            //    Title = touristRouteFromRepo.Title,
            //    Description = touristRouteFromRepo.Description,
            //    Price = touristRouteFromRepo.OriginalPrice * (decimal)(touristRouteFromRepo.DiscountPresent ?? 1),
            //    CreateTime = touristRouteFromRepo.CreateTime,
            //    UpdateTime = touristRouteFromRepo.UpdateTime,
            //    Features = touristRouteFromRepo.Features,
            //    Fees = touristRouteFromRepo.Fees,
            //    Notes = touristRouteFromRepo.Notes,
            //    Rating = touristRouteFromRepo.Rating,
            //    TravelDays = touristRouteFromRepo.TravelDays.ToString(),
            //    TripType = touristRouteFromRepo.TripType.ToString(),
            //    DepartureCity = touristRouteFromRepo.DepartureCity.ToString()
            //};
           var touristRouteDto= _mapper.Map<TouristRoute, TouristRouteDto>(touristRouteFromRepo);
            return Ok(touristRouteDto);
        }
        [HttpPost]
        [Authorize/*(Roles = "Admin")*/]//只有Admin 才可以提交post请求
        [Authorize(AuthenticationSchemes = "Bearer")]
        public async Task<IActionResult> CreateTouristRoutes([FromBody]TouristRouteForCartionDto touristRouteForCartionDto)
        {
            var touristRouteModel = _mapper.Map<TouristRoute>(touristRouteForCartionDto);
            _touristRouteRepository.AddTouristRoutePicture(touristRouteModel);//添加数据
            await _touristRouteRepository.SaveAsync();//保存
            var touristRouteToReture = _mapper.Map<TouristRouteDto>(touristRouteModel);//把新增的数据映射到AutoMapper中
            return CreatedAtRoute("GerTouristRoutesById", new
            {
                tourisId = touristRouteToReture.Id
            }, touristRouteToReture);//返回201

        }
        /*
         * PUT  更新某资源的全部信息    该资源的全部字段    当某些字段被忽略后，信息会被删除
         * PATCH  更新某资源的部分信息  该资源需要被更新的部分字段      patch是在put 之后才被提出来的
         */

        [HttpPut("{touristRoutesId}")]
        [Authorize(AuthenticationSchemes = "Bearer")]
        public async Task<IActionResult> UpdateTouristRoutes([FromRoute] Guid touristRoutesId,[FromBody] TouristRouteUpdateDto touristRouteUpdateDto)
        {
            if ( ! (await _touristRouteRepository.GetTouristRouteExistsAsync(touristRoutesId)))
            {
                return NotFound("找不到该旅游路线");
            }
            //获取旅游路线数据
            var TouristRoutesRpe = await _touristRouteRepository.GetTouristRouteAsync(touristRoutesId);
            //更新数据
            _mapper.Map(touristRouteUpdateDto, TouristRoutesRpe);
            //保存
           await _touristRouteRepository.SaveAsync();
            //status 204
            return NoContent();
        }
        [HttpPatch("{touristRoutesId}")]
        public async Task<IActionResult> PatchTouristRoutes([FromRoute] Guid touristRoutesId,[FromBody]JsonPatchDocument<TouristRouteForUpdateDto> patchDocument)
        {
            if (!(await _touristRouteRepository.GetTouristRouteExistsAsync(touristRoutesId)))
            {
                return NotFound("找不到旅游路线");
            }
            var touristRoutesRep = await  _touristRouteRepository.GetTouristRouteAsync(touristRoutesId);
            var touristRoutesPut = _mapper.Map<TouristRouteForUpdateDto>(touristRoutesRep);
            patchDocument.ApplyTo(touristRoutesPut, ModelState);
            //因为patch提交的是json数据，无法进行数据校验，这里是在把数据提交前进行校验
            if (!TryValidateModel(touristRoutesPut))
            {
                return ValidationProblem(ModelState);
            }
            _mapper.Map(touristRoutesPut, touristRoutesRep);
            await _touristRouteRepository.SaveAsync();
            return NoContent();
        }
        [HttpDelete("{touristRoutesId}")]
        [Authorize(AuthenticationSchemes = "Bearer")]
        public async Task< IActionResult> DeleteTouristRoute([FromRoute] Guid touristRoutesId)
        {
            if (! await _touristRouteRepository.GetTouristRouteExistsAsync(touristRoutesId))
            {
                return NotFound("找不到旅游路线");
            }
            //获取路线路线信息
            var touristRoute = await  _touristRouteRepository.GetTouristRouteAsync(touristRoutesId);
            //删除旅游路线
            _touristRouteRepository.DeleteTouristRoute(touristRoute);
            await _touristRouteRepository.SaveAsync();
            return NoContent();

        }
        [HttpDelete("({touristIDs})")]
        [Authorize(AuthenticationSchemes = "Bearer")]
        public async Task<IActionResult> DeleteTouristRouteById([ModelBinder(BinderType = typeof(ArrayModelBinder))][FromRoute]IEnumerable<Guid> touristIDs) 
        {
            if(touristIDs == null)
            {
                return BadRequest();
            }
           _touristRouteRepository.DeleteTouristRoutes(await _touristRouteRepository.GetTouristRouteByIdsAsync(touristIDs));
            await  _touristRouteRepository.SaveAsync();
            return NoContent();
        }
    }
    
}
